package com.wsfk.ssm.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import maps.com.wsfk.ssm.user.HandBookMapper;
import maps.com.wsfk.ssm.user.UserMapper;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.stereotype.Service;

import com.wsfk.ssm.entity.HandBook;
import com.wsfk.ssm.entity.Picture;
import com.wsfk.ssm.entity.User;
import com.wsfk.ssm.entity.Zip;
import com.wsfk.ssm.path.CallPath;
import com.wsfk.ssm.path.SiteUtil;
import com.wsfk.ssm.tools.CompressImgUtil;
import com.wsfk.ssm.tools.Pagination;

@Service("HandBookSvcImpl")
public class HandBookSvcImpl implements HandBookSvc {
	
	Logger log = Logger.getLogger(this.getClass());

	private HandBookMapper handBookMapper;
	private UserMapper userMapper;
	private FileSvc fileSvc;
	
	
	@Resource
	public void setFileSvc(FileSvc fileSvc) {
		this.fileSvc = fileSvc;
	}

	@Resource
	public void setHandBookMapper(HandBookMapper handBookMapper) {
		this.handBookMapper = handBookMapper;
	}

	// 查找到用户相对应的手册
	public List<HandBook> queryAllBookByUser(String userid) {
		if (StringUtils.isBlank(userid)) {
			return null;
		} else {
			return handBookMapper.queryAllBookByUser(userid);
		}
	}

	public Pagination queryPageBookByUser(String userId, Pagination page) {
		List<HandBook> list = handBookMapper.queryPageBookByUser(userId, 
							  String.valueOf(page.getStartRow()), 
							  String.valueOf(page.getEndRow()));
		int totalCount = handBookMapper.queryPageBookCountByUser(userId);
		page.setTotalCount(totalCount);
		page.setData(list);
		return page;
	}

	public HandBook queryById(String id) {
		if(StringUtils.isBlank(id)){
			return null;
		}else{
			return handBookMapper.queryById(id);
		}
	}

	public int updateHandBookById(HandBook handBook) {
		int i = 0;
		if (handBook != null) {
			handBook.setCreateStatus(HandBook.UNFINISHED);
			i = handBookMapper.updateHandBookById(handBook);
		}
		return i;
	}

	public HandBook queryBookByIdAndPublishStatus(String id) {
		return handBookMapper.queryBookByIdAndPublishStatus(id);	
	}

	
	public int addZip(Zip zip) {
		return handBookMapper.addZip(zip);
	}
	
	public Zip queryZipByFileDir(String fileDir) {
		return handBookMapper.queryZipByFileDir(fileDir);
	}
	
	
	
	
	
	//zip包可以删除了
	public boolean zip(String inputFileName) {
		boolean result = true;
		
		try {
			
			String zipFileName = inputFileName + ".zip";
			File inputFile = new File(inputFileName);
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
					zipFileName));
			
			result = zip(out, inputFile, "");
			
			out.close();
			
		} catch (FileNotFoundException e) {
			result = false;
			log.error("can't write to " + e);
			e.printStackTrace();
		} catch (Exception e) {
			result = false;
			log.error("can't write to " + e);
			e.printStackTrace();
		}
		return result;
	}

	protected boolean zip(ZipOutputStream out, File f, String base) {
		boolean result = true;
		try {
			if (f.isDirectory()) {
				File[] fl = f.listFiles();
				out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
				base = base.length() == 0 ? "" : base + "/";
				for (int i = 0; i < fl.length; i++) {
					zip(out, fl[i], base + fl[i].getName());
				}
			} else {
				out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
				FileInputStream in = new FileInputStream(f);
				int b;
				while ((b = in.read()) != -1) {
					out.write(b);
				}
				in.close();
			}
		} catch (IOException e) {
			result = false;
			log.error("can't write to " + e);
			e.printStackTrace();
		}
		return result;
	}

	

	public boolean savePicFile( User user,HandBook handBook,File upload, String model){
		try {
			fileSvc.saveBook(user, handBook, upload, model);
			
			Picture picture = new Picture();
			picture.setId(UUID.randomUUID().toString());
			picture.setType(Picture.ICON);
			picture.setHandBookId(handBook.getId());
			picture.setFileDir(new CallPath().iconWay(user, handBook).build());
			handBookMapper.addPicture(picture);
			
			handBook.setCreateDate(new Date());
			handBook.setCreateStatus(HandBook.UNFINISHED);
			handBook.setVersion("1");
			handBook.setBookdir(new CallPath().bookWay(user, handBook).build());
			handBookMapper.updateHandBook(handBook);
			
		} catch (IOException e) {
			log.error("File upload problems"+e);
			throw new RuntimeException(e);
		}
		return true;
	}

	public boolean updateVersionById(User u, HandBook b){
		// 查寻
		User user = userMapper.queryById(u.getId());
		Zip zip = handBookMapper.queryZipByBookId(b.getId());
		HandBook book = handBookMapper.queryById(b.getId());
		
		// ZIP文件生成&copy
		fileSvc.saveZip(user, book);
		
		// zip 生成
		String zipPath = new CallPath().zipWay(user, book).build();
		
	
		if(zip==null){
			Zip z = new Zip();
			z.setId(UUID.randomUUID().toString());
			z.setFileDir(zipPath);
			z.setHandBookId(b.getId());
			handBookMapper.addZip(z);			
		}else{
			zip.setHandBookId(zip.getHandBookId());
			zip.setFileDir(zipPath);
			handBookMapper.updateZip(zip);			
		}
		// 修改书的状态为完成
		book.setCreateStatus(HandBook.FINISHED);
		handBookMapper.updateVersionById(book);
		
		return true;
	}
	@Resource
	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
		
	}
}
